package cn.ffcs.uec.wBStaffInfo.action;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Hibernate;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.image.Image;
import org.zkoss.util.media.Media;
import org.zkoss.web.servlet.Servlets;
import org.zkoss.zhtml.Messagebox;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.Filedownload;

import cn.ffcs.raptornuke.plugin.common.zk.ctrl.BasePortletComposer;
import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.raptornuke.portal.model.User;
import cn.ffcs.uec.common.util.NodeVoUtil;
import cn.ffcs.uec.common.util.PermissionUtil;
import cn.ffcs.uec.common.util.UecConstants;
import cn.ffcs.uec.outStaff.manager.UecOutStaffManager;
import cn.ffcs.uec.outStaff.model.PictureTable;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.model.UecDocEdu;
import cn.ffcs.uec.wBStaffInfo.action.bean.WbDocEduEditBean;
import cn.ffcs.uom.common.constants.BaseUnitConstants;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PlatformUtil;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.util.UomZkUtil;
import cn.ffcs.uom.common.vo.NodeVo;

/**
 * 
 * @desc:教育经历新增、编辑
 * @author BMP
 * @date 2019年1月5日
 */
@Controller
@Scope("prototype")
public class WbDocEduEditComposer extends BasePortletComposer{

	private static final long serialVersionUID = 3086340593438520480L;
	
	//学信网学历证书
	private static final String EN = "Education";
	
	//学信网学位证书
	private static final String DE = "degree";
	
	/**
	 * 页面bean
	 */
	private WbDocEduEditBean bean = new WbDocEduEditBean();
	/**
	 * 操作类型
	 */
	private String opType;
	/**
	 * 人员信息
	 */
	private UecOutStaffInfo uecOutStaffInfo;
	/**
	 * 添加教育经历
	 */
	private UecDocEdu uecDocEdu;

	/**
	 * 是否是被外包员工入职申请页面引用
	 */
	//private boolean isOutStaffEntryExt = false;
	
	/**
     * 最高学历毕业证书:高校毕业证书照片
     */
//    private Media certMedia;

    /**
     * 最高学历毕业证书:学信网学历照片
     */
    private Media fiveMedia;
    
    /**
     * 最高学位证书:最高学位证书
     */
//    private Media storeMedia;
    /**
     * 最高学位证书:学信网学位证书
     */
    private Media dEMedia;
    
    private UecOutStaffManager uecOutStaffManager = (UecOutStaffManager) ApplicationContextUtil
            .getBean("uecOutStaffManager");

    
	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		UomZkUtil.autoFitHeight(comp);
		Components.wireVariables(comp, bean);
	}

	/**
	 * 初始化窗口
	 * 
	 * @throws ParseException
	 */
	public void onCreate$wBDocEduEditWindow() throws ParseException {
		this.bindCombobox();
		this.bindBean();
		this.checkEducationAndDegreeIsNo();
		
		/**
		 * 初始化时将所有的下载按钮设置不可见，只有在审批的时候才可见
		 */
//		bean.getDownloadCertButton().setVisible(false);
		bean.getDownloadFiveButton().setVisible(false);
//		bean.getDownloadStoreButton().setVisible(false);
		bean.getDownloadDEButton().setVisible(false);
	}

	/**
	 * 绑定combobox
	 */
	public void bindCombobox() {
		this.bindComboboxBean();
	}
	
	/**
	 * 编辑加载页面是要判断学历、学位是否为无
	 */
	public void checkEducationAndDegreeIsNo() {
		String index = (String) bean.getEducation().getSelectedItem().getValue();
		if ("1001A1100000000006AW".equals(index)) {
			bean.getEducationctifcode().setDisabled(true);
			bean.getGlbdef9().setDisabled(true);
			bean.getGlbdef5().setDisabled(true);
			bean.getLasteducation().setDisabled(true);
			bean.getGlbdef8().setDisabled(true);
			bean.getGlbdef3().setDisabled(true);
			bean.getMajortype().setDisabled(true);
			
			// 清数据
			bean.getEducationctifcode().setValue(null);
			bean.getGlbdef9().setSelectedIndex(0);
			bean.getGlbdef5().setSelectedIndex(0);
			bean.getLasteducation().setSelectedIndex(0);
			bean.getGlbdef8().setSelectedIndex(0);
			bean.getGlbdef3().setValue(null);
			bean.getMajortype().setSelectedIndex(0);
		} 
		String index1 = (String) bean.getPkDegree().getSelectedItem().getValue();
		if ("1001A1100000000006B3".equals(index1)) {
			bean.getCertifcode().setDisabled(true);
			bean.getDegreedate().setDisabled(true);
			bean.getDegreeunit().setDisabled(true);
			bean.getGlbdef4().setDisabled(true);
	
			// 清理数据
			bean.getCertifcode().setValue(null);
			bean.getDegreedate().setValue(null);
			bean.getDegreeunit().setValue(null);
			bean.getGlbdef4().setSelectedIndex(0);
		} 
	}

	/**
	 * 监听学历下拉选择事件
	 */
	public void onSelect$education() {
		String index = (String) bean.getEducation().getSelectedItem().getValue();
		if ("1001A1100000000006AW".equals(index)) {
			bean.getEducationctifcode().setDisabled(true);
			bean.getGlbdef9().setDisabled(true);
			bean.getGlbdef5().setDisabled(true);
			bean.getLasteducation().setDisabled(true);
			bean.getGlbdef8().setDisabled(true);
			bean.getGlbdef3().setDisabled(true);
			bean.getMajortype().setDisabled(true);
			
            //设置学信网学历证书不可见
            //bean.getDownloadFiveButton().setVisible(false);
            bean.getUploadFiveButton().setVisible(false);
            bean.getFivePic().setVisible(false);
            
			// 清数据
			bean.getEducationctifcode().setValue(null);
			bean.getGlbdef9().setSelectedIndex(0);
			bean.getGlbdef5().setSelectedIndex(0);
			bean.getLasteducation().setSelectedIndex(0);
			bean.getGlbdef8().setSelectedIndex(0);
			bean.getGlbdef3().setValue(null);
			bean.getMajortype().setSelectedIndex(0);
		} else {
			bean.getEducationctifcode().setDisabled(false);
			bean.getGlbdef9().setDisabled(false);
			bean.getGlbdef5().setDisabled(false);
			bean.getLasteducation().setDisabled(false);
			bean.getGlbdef8().setDisabled(false);
			bean.getGlbdef3().setDisabled(false);
			bean.getMajortype().setDisabled(false);
			
            //设置学信网学历证书不可见
            //bean.getDownloadFiveButton().setVisible(false);
            bean.getUploadFiveButton().setVisible(true);
            bean.getFivePic().setVisible(true);
			
			
		}
	}

	/**
	 * 监听学位下拉选择
	 */
	public void onSelect$pkDegree() {
		String index = (String) bean.getPkDegree().getSelectedItem().getValue();
		if ("1001A1100000000006B3".equals(index)) {
			bean.getCertifcode().setDisabled(true);
			bean.getDegreedate().setDisabled(true);
			bean.getDegreeunit().setDisabled(true);
			bean.getGlbdef4().setDisabled(true);
			
            //学信网学位证书
            //bean.getDownloadDEButton().setVisible(false);
            bean.getUploadDEButton().setVisible(false);
            bean.getDEPic().setVisible(false);
            
			// 清理数据
			bean.getCertifcode().setValue(null);
			bean.getDegreedate().setValue(null);
			bean.getDegreeunit().setValue(null);
			bean.getGlbdef4().setSelectedIndex(0);
		} else {
			bean.getCertifcode().setDisabled(false);
			bean.getDegreedate().setDisabled(false);
			bean.getDegreeunit().setDisabled(false);
			bean.getGlbdef4().setDisabled(false);
			
            //学信网学位证书
            //bean.getDownloadDEButton().setVisible(false);
            bean.getUploadDEButton().setVisible(true);
            bean.getDEPic().setVisible(true);
		}
	}
	
	/**
	 * 监听 是否是最高学历
	 */
	public void onSelect$lasteducation(){
		String index = (String) bean.getLasteducation().getSelectedItem().getValue();
		if("Y".equals(index)){
          //学信网学位证书
          //bean.getDownloadDEButton().setVisible(false);
          bean.getUploadDEButton().setVisible(true);
          bean.getDEPic().setVisible(true);
		}else{
          //学信网学位证书
          //bean.getDownloadDEButton().setVisible(false);
          bean.getUploadDEButton().setVisible(false);
          bean.getDEPic().setVisible(false);
		}
	}

	/**
	 * bindBean
	 * 
	 * @throws ParseException
	 */
	public void bindBean() throws ParseException {
		opType = (String) arg.get("opType");
		//isOutStaffEntryExt = (Boolean) arg.get("isOutStaffEntryExt");
		if ("add".equals(opType)) {
			this.bean.getWBDocEduEditWindow().setTitle("新增教育经历信息");
			bean.getUecOutDocEduEditDiv().setHeight("30%");
			uecOutStaffInfo = (UecOutStaffInfo) arg.get("uecOutStaffInfo");
		}
		if ("view".equals(opType)) {
			this.bean.getWBDocEduEditWindow().setTitle("查看教育经历信息");
			uecDocEdu = (UecDocEdu) arg.get("uecDocEdu");
			if (null != uecDocEdu) {
				PubUtil.fillBeanFromPo(uecDocEdu, bean);
				stringTransToDate();
				bean.getButtonDiv().setVisible(false);
				PubUtil.disableComponent(bean.getWBDocEduEditWindow(), true);
			}
		}
		if ("edit".equals(opType)) {
			this.bean.getWBDocEduEditWindow().setTitle("编辑教育经历信息");
			bean.getUecOutDocEduEditDiv().setHeight("30%");
			uecDocEdu = (UecDocEdu) arg.get("uecDocEdu");
			uecOutStaffInfo = (UecOutStaffInfo) arg.get("uecOutStaffInfo");
			if (null != uecDocEdu) {
				PubUtil.fillBeanFromPo(uecDocEdu, bean);
				stringTransToDate();
			}

		}
		if ("approvalEdit".equals(opType)) {
			this.bean.getWBDocEduEditWindow().setTitle("编辑审批教育经历信息");
			bean.getUecOutDocEduEditDiv().setHeight("30%");
			uecDocEdu = (UecDocEdu) arg.get("uecDocEdu");
			uecOutStaffInfo = (UecOutStaffInfo) arg.get("uecOutStaffInfo");
			if (null != uecDocEdu) {
				PubUtil.fillBeanFromPo(uecDocEdu, bean);
				stringTransToDate();
			}
		}
	}

	public void startAddProcess() throws Exception {

		// 判断该人员是否在审状态，如果是在审状态不允许再次发起此流程
		boolean isOnApproval = ApprovalUtil.isOnApproval(ApprovalConstants.OUT_STAFF_EDU_ADD_PROC_DEF_ID,
				uecOutStaffInfo.getOutStaffId());
		if (isOnApproval) {
			ZkUtil.showError("有教育经历新增记录处于在审状态，不允许发起！", "错误提示");
			return;
		}

		if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
			ZkUtil.showError("当前登录用户不存在!", "错误提示");
			return;
		}
		String currentName = PlatformUtil.getCurrentUser().getScreenName();
		// 新增走流程状态为1320状态
		instantOfUecEdu(currentName);

		if (ApprovalUtil.getActivityFlag() || PermissionUtil.isNoMainOutStaff()) {
			uecDocEdu.addStatusCdIS3();

			String formTheme = "盟市外包人员教育经历新增流程";
			String startFlowJson = "{" + "formTheme: '" + formTheme + "',"
					+ " formContent: '教育经历新增人员:" + uecOutStaffInfo.getPsnName()
					+ "'," + " procDefId: '"
					+ ApprovalConstants.OUT_STAFF_EDU_ADD_PROC_DEF_ID + "',"
					+ " urgent: '1'," + " atiActCategoryId: '"
					+ ApprovalConstants.MODIFICATION_CATEGORY_ID + "',"
					+ " procDefKey: '" + ApprovalUtil.OUT_STAFF_EDU_ADD + "',"
					+ " formSender: '" + currentName + "'," + " primaryId: '{"
					+ "uec_out_staff_info_his:"
					+ uecOutStaffInfo.getOutStaffId() + ",uec_out_staff_info:"
					+ uecOutStaffInfo.getOutStaffId() + ",uec_doc_edu:"
					+ uecDocEdu.getEduId() + "'}";

			String procInstId = null;
			try {
				procInstId = ApprovalUtil.startApproval(startFlowJson);
			} catch (Exception e) {
				uecDocEdu.removeOnly();
				onCancel();
				ZkUtil.showError("流程发起失败！", "错误提示");
				e.printStackTrace();
			}

			if (StrUtil.isNullOrEmpty(procInstId)) {
				uecDocEdu.removeOnly();
				onCancel();
				ZkUtil.showError("流程发起失败！", "错误提示");
				return;
			}
			// 第一审批人如果是发起人直接到人力审批环节
			ApprovalUtil.isCurrentAssignNames(procInstId);
			ApprovalUtil.showNextAssignee(procInstId, formTheme);
		} else {
			// 数据直接入库
			uecDocEdu.addOnly();
			ZkUtil.showInformation("数据已保存成功!", "温馨提示");
		}

	}

	public void startEditProcess() throws Exception {

		if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
			ZkUtil.showError("当前登录用户不存在!", "错误提示");
			return;
		}

		String currentName = PlatformUtil.getCurrentUser().getScreenName();

		PubUtil.fillPoFromBean(bean, uecDocEdu);
		dateTransToString();
		uecDocEdu.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
		uecDocEdu.setModifier(currentName);
		uecDocEdu.setModifiedtime(DateUtil.getCurrenDate());
		Long uecEduIdHis = uecDocEdu.getEduId();
		
//		instantOfUecEdu(currentName);

		
		/**
		 * if(PermissionUtil.isNoMainOutStaff()) == true
		 *  add 这个流程判断是否是 普通外包人员，如果是则允许发起流程，此时不再从数据库判断 流程开关
		 */
		// 发起流程
		if (ApprovalUtil.getActivityFlag()) {			
			// 判断该人员是否在审状态，如果是在审状态不允许再次发起此流程
			boolean isOnApproval = ApprovalUtil.isOnApproval(ApprovalConstants.OUT_STAFF_EDU_EDIT_PROC_DEF_ID,
					uecOutStaffInfo.getOutStaffId());
			if (isOnApproval) {
				ZkUtil.showError("在审状态不允许发起！", "错误提示");
				return;
			}
			uecDocEdu.addStatusCdIS3();
			Long uecEduId = uecDocEdu.getEduId();


			String formTheme = "盟市外包人员教育经历修改流程";
			String startFlowJson = "{" + "formTheme: '" + formTheme + "',"
					+ " formContent: '教育经历修改人员:" + uecOutStaffInfo.getPsnName()
					+ "'," + " procDefId: '"
					+ ApprovalConstants.OUT_STAFF_EDU_EDIT_PROC_DEF_ID + "',"
					+ " urgent: '1'," + " atiActCategoryId: '"
					+ ApprovalConstants.MODIFICATION_CATEGORY_ID + "',"
					+ " procDefKey: '" + ApprovalUtil.OUT_STAFF_EDU_EDIT + "',"
					+ " formSender: '" + currentName + "'," + " primaryId: '{"
					+ "uec_out_staff_info_his:"
					+ uecOutStaffInfo.getOutStaffId() + ",uec_out_staff_info:"
					+ uecOutStaffInfo.getOutStaffId() + ",uec_doc_edu_his:"
					+ uecEduIdHis + ",uec_doc_edu:" + uecEduId + "'}";

			String procInstId = null;
			try {
				procInstId = ApprovalUtil.startApproval(startFlowJson);
			} catch (Exception e) {
				uecDocEdu.removeOnly();
				onCancel();
				ZkUtil.showError("流程发起失败！", "错误提示");
				e.printStackTrace();
			}

			if (StrUtil.isNullOrEmpty(procInstId)) {
				uecDocEdu.removeOnly();
				onCancel();
				ZkUtil.showError("流程发起失败！", "错误提示");
				return;
			}
			// 第一审批人如果是发起人直接到人力审批环节
			ApprovalUtil.isCurrentAssignNames(procInstId);
			ApprovalUtil.showNextAssignee(procInstId, formTheme);
		} else {
			// 直接更新数据
			uecDocEdu.updateOnly();
			ZkUtil.showInformation("数据已更新成功!", "温馨提示");

		}

	}

	/**
	 * 保存
	 * 
	 * @throws Exception
	 */
	public void onOk() throws Exception {
		User currentUser = PlatformUtil.getCurrentUser();
		if (StrUtil.isNullOrEmpty(currentUser)) {
			ZkUtil.showError("当前登录用户已失效，请重新登录!", "错误提示");
			return;
		}
		String currentName = PlatformUtil.getCurrentUser().getScreenName();
		if ("add".equals(opType)) {
			//新增校验
			String msg = this.checkUacStaffData();
			if (null != msg) {
				Messagebox.show(msg);
				return;
			}
			
			instantOfUecEdu(currentName);
			// 如果是由外包员工入职页面引用，不走流程；其他页面引用走流程；
			//if (!isOutStaffEntryExt) {
				startAddProcess();
			//}
	        // 上传相关图片
	        if(null != fiveMedia) {	           
	            saveMedia(fiveMedia, uecOutStaffInfo, EN);
	        }
	        // 上传学位照片
	        if(null != dEMedia) {  
	            saveMedia(dEMedia, uecOutStaffInfo, DE);
	        }
			Events.postEvent("onOK", this.self, uecDocEdu);			
			this.onCancel();
		}
		if ("edit".equals(opType)) {
			//编辑校验
			String msg = this.editCheckUacStaffData();
			if (null != msg) {
				Messagebox.show(msg);
				return;
			}
			PubUtil.fillPoFromBean(bean, uecDocEdu);
			/**
			 * 编辑时，需要判断：
			 *--学历：
			 * 1：如果低于大专，则不需要上传学历的
			 * 2：如果高于大专，则需要上传学历
			 * 3：无学历，不需要上传
			 * 
			 *--学位：
			 * 1：学位不为无，是最高学位，需要上传
			 * 2：学位为无，不需要上传
			 */
			// 上传学位照片
	        if(null != dEMedia) {  
	            saveMedia(dEMedia, uecOutStaffInfo, DE);
	        }
	        String pkDegree = uecDocEdu.getPkDegree();//学位
	        String glbdef4 = uecDocEdu.getGlbdef4();//是否是最高学位
	        if("1001A1100000000006B3".equals(pkDegree)){
	        	glbdef4 = "N";
	        }	
			if("Y".equals(glbdef4)){
				boolean existPicDe = isExistPic(uecOutStaffInfo, DE);//判断数据库中是否有
				if(!existPicDe){
					ZkUtil.showError("请上传学位证书照片!", "温馨提示");
					return;
				}
			}

			if(null != fiveMedia){
				saveMedia(fiveMedia, uecOutStaffInfo, EN);
			}
			String education = uecDocEdu.getEducation();//学历
			boolean junior = isHigherThanJunior(education);//判断学历是否大于等于大专
			if(junior){
				boolean existPicEn = isExistPic(uecOutStaffInfo, EN);//判断数据库中是否有
				if(!existPicEn){
					ZkUtil.showError("请上传学历证书照片!", "温馨提示");
					return;
				}
			}
			
			// 如果是由外包员工入职页面引用，不走流程；其他页面引用走流程；
			startEditProcess();
			/*if (!isOutStaffEntryExt) {
				startEditProcess();
			} else {
				modificateOfUecEdu(currentName);
			}*/
			modificateOfUecEdu(currentName);
			Events.postEvent("onOK", this.self, uecDocEdu);
			this.onCancel();
		}
		if ("approvalEdit".equals(opType)) {
			modificateOfUecEdu(currentName);
			uecDocEdu.updateOnly();
			Events.postEvent("onOK", this.self, uecDocEdu);
			this.onCancel();
		}
	}

	/**
	 * 取消
	 */
	public void onCancel() {
		// 关闭窗口
		this.bean.getWBDocEduEditWindow().onClose();
	}

	/**
	 * 添加一个uecEdu对象
	 * 
	 * @param currentName
	 * @throws IOException 
	 * @throws InterruptedException 
	 */
	private void instantOfUecEdu(String currentName) throws IOException, InterruptedException {
		uecDocEdu = UecDocEdu.newInstance();
		PubUtil.fillPoFromBean(bean, uecDocEdu);
		dateTransToString();
		uecDocEdu.setStaffId(uecOutStaffInfo.getOutStaffId());
		uecDocEdu.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
		uecDocEdu.setPkPsndoc(uecOutStaffInfo.getPkPsnMsg());
		uecDocEdu.setCreator(currentName);
        uecDocEdu.setCreationtime(DateUtil.getCurrenDate());
        //uecDocEdu.addOnly();
	}

	/**
	 * 修改一个uecEdu对象
	 * 
	 * @param currentName
	 */
	private void modificateOfUecEdu(String currentName) {
		PubUtil.fillPoFromBean(bean, uecDocEdu);
		dateTransToString();
		uecDocEdu.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
		uecDocEdu.setModifier(currentName);
		uecDocEdu.setModifiedtime(DateUtil.getCurrenDate());
		//uecDocEdu.updateOnly();
	}

	/**
	 * 新增检测填入的参数是否为空
	 */
	private String checkUacStaffData() {
		if (StrUtil.isNullOrEmpty(bean.getSchool().getValue())) {
			return "请填写学校名称";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef1().getSelectedItem().getValue())) {
			return "请选择学校类别";
		} else if (StrUtil.isNullOrEmpty(bean.getStudymode().getSelectedItem().getValue())) {
			return "请选择学习方式";
		} else if (StrUtil.isNullOrEmpty(bean.getEdusystem().getValue())) {
			return "请填写学制";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef2().getValue())) {
			return "请填写所在院系";
		} else if (StrUtil.isNullOrEmpty(bean.getMajor().getValue())) {
			return "请填写专业";
		}
		if (!StrUtil.isNullOrEmpty(bean.getEducation().getSelectedItem().getValue())) {
		    //判断学历是否为 无
			if (!"1001A1100000000006AW".equals(bean.getEducation().getSelectedItem().getValue())) {
				if (StrUtil.isNullOrEmpty(bean.getMajortype().getSelectedItem().getValue())) {
					return "请选择学历专业类别";
				} else if (StrUtil.isNullOrEmpty(bean.getGlbdef3().getValue())) {
					return "请选择取得学历时间";
				} else if (StrUtil.isNullOrEmpty(bean.getEducationctifcode().getValue())) {
					return "请填写学历证书编号";
				} else if (StrUtil.isNullOrEmpty(bean.getGlbdef5().getSelectedItem().getValue())) {
					return "请选择是否第一学历";
				} else if (StrUtil.isNullOrEmpty(bean.getGlbdef8().getSelectedItem().getValue())) {
					return "请选择是否全日制最高学历";
				} else if (StrUtil.isNullOrEmpty(bean.getLasteducation().getSelectedItem().getValue())) {
					return "请选择是否最高学历";
				} else if (StrUtil.isNullOrEmpty(bean.getGlbdef9().getSelectedItem().getValue())) {
					return "请选择是否在职最高学历";
				}  
				//判断学历是否大于等于专科
				boolean junior = isHigherThanJunior((String)bean.getEducation().getSelectedItem().getValue());
				if(junior){
					if(null == fiveMedia)
					return "学信网学历证书图片";
				}			
			}
		}
		if (!StrUtil.isNullOrEmpty(bean.getPkDegree().getSelectedItem().getValue())) {
		    //判断学位是否为无
			if (!"1001A1100000000006B3".equals(bean.getPkDegree().getSelectedItem().getValue())) {
				if (StrUtil.isNullOrEmpty(bean.getGlbdef4().getSelectedItem().getValue())) {
					return "请选择是否最高学位";
				} else if (StrUtil.isNullOrEmpty(bean.getDegreedate().getValue())) {
					return "请填写学位授予日期";
				} else if (StrUtil.isNullOrEmpty(bean.getCertifcode().getValue())) {
					return "请填写学位证书编号";
				} else if (StrUtil.isNullOrEmpty(bean.getDegreeunit().getValue())) {
					return "请填写学位授予单位";
				}
				if("Y".equals(bean.getGlbdef4().getSelectedItem().getValue())) {
	                if(null == dEMedia) {
	                    return "学信网学位证书图片";
	                }
	            }   
			}
		}
		return null;
	}
	
	/**
	 * 编辑校验
	 * @Title: editCheckUacStaffData   
	 * @Description: TODO 
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	private String editCheckUacStaffData() {
		if (StrUtil.isNullOrEmpty(bean.getSchool().getValue())) {
			return "请填写学校名称";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef1().getSelectedItem().getValue())) {
			return "请选择学校类别";
		} else if (StrUtil.isNullOrEmpty(bean.getStudymode().getSelectedItem().getValue())) {
			return "请选择学习方式";
		} else if (StrUtil.isNullOrEmpty(bean.getEdusystem().getValue())) {
			return "请填写学制";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef2().getValue())) {
			return "请填写所在院系";
		} else if (StrUtil.isNullOrEmpty(bean.getMajor().getValue())) {
			return "请填写专业";
		}
		if (!StrUtil.isNullOrEmpty(bean.getEducation().getSelectedItem().getValue())) {
		    //判断学历是否为 无
			if (!"1001A1100000000006AW".equals(bean.getEducation().getSelectedItem().getValue())) {
				if (StrUtil.isNullOrEmpty(bean.getMajortype().getSelectedItem().getValue())) {
					return "请选择学历专业类别";
				} else if (StrUtil.isNullOrEmpty(bean.getGlbdef3().getValue())) {
					return "请选择取得学历时间";
				} else if (StrUtil.isNullOrEmpty(bean.getEducationctifcode().getValue())) {
					return "请填写学历证书编号";
				} else if (StrUtil.isNullOrEmpty(bean.getGlbdef5().getSelectedItem().getValue())) {
					return "请选择是否第一学历";
				} else if (StrUtil.isNullOrEmpty(bean.getGlbdef8().getSelectedItem().getValue())) {
					return "请选择是否全日制最高学历";
				} else if (StrUtil.isNullOrEmpty(bean.getLasteducation().getSelectedItem().getValue())) {
					return "请选择是否最高学历";
				} else if (StrUtil.isNullOrEmpty(bean.getGlbdef9().getSelectedItem().getValue())) {
					return "请选择是否在职最高学历";
				}
			}
		}
		if (!StrUtil.isNullOrEmpty(bean.getPkDegree().getSelectedItem().getValue())) {
		    //判断学位是否为无
			if (!"1001A1100000000006B3".equals(bean.getPkDegree().getSelectedItem().getValue())) {
				if (StrUtil.isNullOrEmpty(bean.getGlbdef4().getSelectedItem().getValue())) {
					return "请选择是否最高学位";
				} else if (StrUtil.isNullOrEmpty(bean.getDegreedate().getValue())) {
					return "请填写学位授予日期";
				} else if (StrUtil.isNullOrEmpty(bean.getCertifcode().getValue())) {
					return "请填写学位证书编号";
				} else if (StrUtil.isNullOrEmpty(bean.getDegreeunit().getValue())) {
					return "请填写学位授予单位";
				}
			}
		}
		return null;
	}

	/**
	 * 将Date类型时间转成String类型 Date --> String 一套模型，两套标准：日期类型需要格式化
	 */
	public void dateTransToString() {
		if (!StrUtil.isNullOrEmpty(bean.getDegreedate().getValue())) {
			// 学位授予日期
			uecDocEdu.setDegreedate(DateUtil.dateToStr(bean.getDegreedate().getValue()));
		}
		if (!StrUtil.isNullOrEmpty(bean.getGlbdef3().getValue())) {
			// 取得学历时间
			uecDocEdu.setGlbdef3(DateUtil.dateToStr(bean.getGlbdef3().getValue()));
		}
		if (!StrUtil.isNullOrEmpty(bean.getBegindate().getValue())) {
			// 入学日期
			uecDocEdu.setBegindate(DateUtil.dateToStr(bean.getBegindate().getValue()));
		}
		if (!StrUtil.isNullOrEmpty(bean.getEnddate().getValue())) {
			// 毕业日期
			uecDocEdu.setEnddate(DateUtil.dateToStr(bean.getEnddate().getValue()));
		}
	}

	/**
	 * 将String类型的时间转换成Date类型
	 * 
	 * @throws ParseException
	 */
	public void stringTransToDate() throws ParseException {
		// 时间类型转换：String --> Date
		// 学位授予日期
		if (null != uecDocEdu.getDegreedate()) {
			bean.getDegreedate().setValue(DateUtil.patternStrToDate(uecDocEdu.getDegreedate()));
		}
		// 取得学历时间
		if (null != uecDocEdu.getGlbdef3()) {
			bean.getGlbdef3().setValue(DateUtil.patternStrToDate(uecDocEdu.getGlbdef3()));
		}
		// 入学日期
		if (null != uecDocEdu.getBegindate()) {
			bean.getBegindate().setValue(DateUtil.patternStrToDate(uecDocEdu.getBegindate()));
		}
		// 毕业日期
		if (null != uecDocEdu.getEnddate()) {
			bean.getEnddate().setValue(DateUtil.patternStrToDate(uecDocEdu.getEnddate()));
		}

	}

	/**
	 * 未采用数据字典，这里是暂时的转换,将枚举量翻译
	 */
	public void bindComboboxBean() {
		// 学校类别
		ListboxUtils.rendererForEdit(bean.getGlbdef1(), NodeVoUtil.getDictionaries(UecConstants.SCHOOL_TYPE));
		// 学习方式studymode
		ListboxUtils.rendererForEdit(bean.getStudymode(), NodeVoUtil.getDictionaries(UecConstants.STUDY_MODE));
		// 学历education
		ListboxUtils.rendererForEdit(bean.getEducation(), NodeVoUtil.getDictionaries(UecConstants.EDUCATION));
		// 学位pkDegree
		ListboxUtils.rendererForEdit(bean.getPkDegree(), NodeVoUtil.getDictionaries(UecConstants.ACADEMIC_DEGREE));
		// 学历专业类别majortype
		ListboxUtils.rendererForEdit(bean.getMajortype(), NodeVoUtil.getDictionaries(UecConstants.MAJOR_TYPE));

		// 是否第一学历
		List<NodeVo> nodeVoIshiskeypsnList = new ArrayList<NodeVo>();
		String[][] ishiskeypsn = { { "Y", "是" }, { "N", "否" } };
		for (int i = 0; i < ishiskeypsn.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(ishiskeypsn[i][j]);
				nodeVo.setName(ishiskeypsn[i][j + 1]);
			}
			nodeVoIshiskeypsnList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getGlbdef5(), nodeVoIshiskeypsnList);
		// 是否最高学历
		ListboxUtils.rendererForEdit(bean.getLasteducation(), nodeVoIshiskeypsnList);
		// 是否最高学位
		ListboxUtils.rendererForEdit(bean.getGlbdef4(), nodeVoIshiskeypsnList);
		// 是否全日制最高学历
		ListboxUtils.rendererForEdit(bean.getGlbdef8(), nodeVoIshiskeypsnList);
		// 是否在职最高学历
		ListboxUtils.rendererForEdit(bean.getGlbdef9(), nodeVoIshiskeypsnList);
	}

    /**
     * 图片上传：学信网学历证书
     * @param event
     * @throws Exception
     */
	public void onUpload$uploadFiveButton(final ForwardEvent forwardEvent)
			throws Exception {

		Messagebox.show("确认上传此照片？", "上传确认", Messagebox.OK | Messagebox.CANCEL,
				Messagebox.QUESTION, new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						if (((Integer) event.getData()).intValue() == Messagebox.OK) {
							fiveMedia = ((UploadEvent) forwardEvent.getOrigin())
									.getMedia();

							if (null == fiveMedia) {
								ZkUtil.showError("请选择要上传的图片!", "系统提示");
								return;
							} else if (!(fiveMedia.getName().endsWith(".jpg"))) {
								fiveMedia = null;
								ZkUtil.showError("上传的图片不是jpg类型!", "系统提示");
								return;
							}

							showPic(fiveMedia, bean.getFivePic());
						}
					}
				});

	}
   
    /**
     * 图片上传：学信网学位证书图片
     * @param event
     * @throws Exception
     */
	public void onUpload$uploadDEButton(final ForwardEvent forwardEvent)
			throws Exception {

		Messagebox.show("确认上传此照片？", "上传确认", Messagebox.OK | Messagebox.CANCEL,
				Messagebox.QUESTION, new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						if (((Integer) event.getData()).intValue() == Messagebox.OK) {
							dEMedia = ((UploadEvent) forwardEvent.getOrigin())
									.getMedia();

							if (null == dEMedia) {
								ZkUtil.showError("请选择要上传的图片!", "系统提示");
								return;
							} else if (!(dEMedia.getName().endsWith(".jpg"))) {
								dEMedia = null;
								ZkUtil.showError("上传的图片不是jpg类型!", "系统提示");
								return;
							}

							showPic(dEMedia, bean.getDEPic());
						}
					}
				});

	}
    
    /**
     * 下载图片 学信网学历证书
     * @throws SQLException 
     * @throws IOException 
     */
    public void onDownloadFive() throws SQLException, IOException {
        onDownloadPic(uecDocEdu,EN);
    }
    
    /**
     * 下载图片 学信网学位证书
     * @throws SQLException 
     * @throws IOException 
     */
    public void onDownloadDE() throws SQLException, IOException {
        onDownloadPic(uecDocEdu,DE);
    }
    
    /**
     * 设置图片显示的宽高
     * @param picMedia
     * @param picImage
     */
    public void showPic(Media picMedia, org.zkoss.zul.Image picImage) {
        Image img = (Image) picMedia;
        picImage.setHeight("50px");
        picImage.setWidth("50px");

        picImage.setContent(img);
    }
    
    /**
     * 保存图片
     * 将图片转二进制保存在数据库中
     * 注意：一个人员只能上传四张照片：毕业证书照片、学信网学历照片、最高学位证书、学信网学位证书图片
     * 根据这个人的员工编码和照片类型来确定唯一值，如果重复则update;否则add
     * @param picMedia
     * @throws IOException 
     */
    public void saveMedia(Media picMedia,UecOutStaffInfo uecOutStaffInfo, String picType) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(
                picMedia.getByteData()); 
        @SuppressWarnings("deprecation")
        Blob blob = Hibernate.createBlob(bais);
        PictureTable pic = new PictureTable();
        pic.setStaffCode(uecOutStaffInfo.getPsnCode());
        pic.setPicType(picType);
        pic = uecOutStaffManager.isExitPictureTable(pic);
        if(null == pic) {
            pic = PictureTable.newInstance();
            pic.setStaffCode(uecOutStaffInfo.getPsnCode());
            pic.setPicType(picType);
            pic.setPicName(picMedia.getName());
            pic.setPicture(blob);
            pic.addOnly();
        }else {
            pic.setPicName(picMedia.getName());
            pic.setPicture(blob);
            pic.updateOnly();
        }
    }
    
    /**
     * 判断是否存在相关证书
     * @Title: isExistPic   
     * @Description: TODO 
     * @param: @param picMedia
     * @param: @param uecOutStaffInfo
     * @param: @param picType
     * @param: @return
     * @param: @throws IOException      
     * @return: boolean      
     * @throws
     */
    public boolean isExistPic(UecOutStaffInfo uecOutStaffInfo, String picType) throws IOException {
        PictureTable pic = new PictureTable();
        pic.setStaffCode(uecOutStaffInfo.getPsnCode());
        pic.setPicType(picType);
        pic = uecOutStaffManager.isExitPictureTable(pic);
        if(null == pic) {
        	//不存在
        	return false;
        }
        //存在
        return true;
    }
    
    /**
     * 下载图片 根据图片类型flag
     * @throws SQLException 
     * @throws IOException 
     */
    public void onDownloadPic(UecDocEdu uecDocEdu, String picType)
            throws SQLException, IOException {
        try {
            UecOutStaffInfo uec = new UecOutStaffInfo();
            uec.setOutStaffId(uecDocEdu.getStaffId());
            UecOutStaffInfo outStaff = uecOutStaffManager.findUecOutStaffInfoByOutStaffId(uec);
            if (null != outStaff) {
                PictureTable picture = uecOutStaffManager.getPicture(outStaff.getPsnCode(),
                        picType);
                if (null != picture) {
                    String charset = "UTF-8";
                    // 图片名称
                    String fileName = picture.getPicName();
                    // 编码后文件名
                    String encodedName = null;
                    encodedName = URLEncoder.encode(fileName, charset);
                    // 将空格替换为+号
                    encodedName = encodedName.replace("%20", "+");
                    HttpServletRequest httpRequest = (HttpServletRequest) Executions.getCurrent()
                            .getNativeRequest();
                    // 解决ie6 bug 或者是火狐浏览器
                    if (encodedName.length() > 150 || Servlets.isGecko(httpRequest)
                            || Servlets.isGecko3(httpRequest)) {
                        encodedName = new String(fileName.getBytes(charset), "ISO8859-1");
                    }
                    // 获取图片
                    /**
                     * Blob字段的所有操作必须在事物中进行，否则只保存对象的引用，走出事物就失效了
                     */
                    byte[] bs = uecOutStaffManager.getPictureInputStream(outStaff.getPsnCode(),
                            picType);
                    if (null != bs) {
                        Filedownload.save(bs, "application/x-jpg", encodedName);
                    } else {
                        ZkUtil.showError("下载图片失败,图片不存在", "系统提示");
                    }
                }else {
                    ZkUtil.showError("下载图片失败,图片不存在", "系统提示");
                }
            }
        } catch (UnsupportedEncodingException e) {
            ZkUtil.showError("下载图片失败，文件名不支持", "系统提示");
        }
    }
    
    /**
     * 判断学历是否大于等于大专
     * @Title: is   
     * @Description: TODO 
     * @param: @param pkDegree
     * @param: @return      
     * @return: boolean      
     * @throws
     */
    public boolean isHigherThanJunior(String pkDegree){
    	String[] ishiskeypsn = {"1001A1100000000006AM","1001A1100000000006AN",
    			"1001A1100000000006AO","1001A1100000000006AP","1001A1100000000006AQ","1001A1100000000006AX" };
		for (int i = 0; i < ishiskeypsn.length; i++) {
			boolean equals = ishiskeypsn[i].equals(pkDegree);
			if(equals){
				return equals;
			}
		}
    	return false;
    }
    
   
}
